"""
第一个FastAPI程序， 增删改查学生功能
需要安装依赖
    pip install uvicorn
    pip install fastapi
    启动：python firstapp.py
"""
import os
import uvicorn
import time
import json
from fastapi import FastAPI, Query
from fastapi.staticfiles import StaticFiles

#定义一个web服务
app = FastAPI(
    debug=True,
    docs_url="/docs",
    title="增删改查案例"
)

def table_data(total:int, rows):
    return{
        "code":200,
        "msg":"success",
        "total":total,
        "rows":rows
    }

def success(msg, data=None):
    return {
        "code":200,
        "msg":msg,
        "data":data
    }

def fail(msg, data=None):
    return {
        "code":500,
        "msg":msg,
        "data":data
    }

#案例1 学生信息增删改查
#学生列表查询
@app.get("/student/list", tags=['学生管理'])
def get_all_students(
    page:int  = Query(default=1),
    limit:int = Query(default=10)
):
    students = json.load(open("./students.json","r",encoding="utf8"))
    start_post = (page-1)*limit
    return table_data(
        len(students), 
        students[start_post: start_post+limit]
    )

#添加学生
@app.post("/student/add", tags=['学生管理'])
def add_student( 
    name:str, 
    age:int  
):
    student_id = int(open("./id.txt","r").read())
    with open("./id.txt","w") as f:
        f.write(str(student_id+1))
    
    students = json.load(open("./students.json","r",encoding="utf8"))

    students.append({
        "id":student_id,
        "name":name,
        "age":age
    })

    json.dump(students, open("./students.json","w",encoding="utf8"), ensure_ascii=False)
    return {"code":200, "msg":"添加成功"}

#修改学生
@app.post("/student/edit", tags=['学生管理'])
def edit_student(
    id:int,
    name:str, 
    age:int 
):
    students = json.load(open("./students.json","r",encoding="utf8"))

    for i in range(len(students)):
        if students[i]['id']==id:
            students[i]['name'] = name
            students[i]['age'] = age
    

    json.dump(students, open("./students.json","w",encoding="utf8"), ensure_ascii=False)
    return {"code":200, "msg":"修改成功"}

#删除学生
@app.post("/student/del", tags=['学生管理'])
def del_student(
    id:int
):
    students = json.load(open("./students.json","r",encoding="utf8"))

    students = [stu for stu in students if stu['id']!=id]        
    

    json.dump(students, open("./students.json","w",encoding="utf8"), ensure_ascii=False)
    return {"code":200, "msg":"删除成功"}

#挂在静态资源目录
path = os.path.join(os.getcwd(), "example09/www")
#挂在静态资源目录
app.mount(
    "/www", 
    StaticFiles(directory=path),
    name="www"
)

if __name__ == '__main__':
    uvicorn.run(
        app="example09:app",
        host="127.0.0.1",
        port=8899,
        reload=True
    )



